﻿using System.IO;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Shell;

namespace BlogTruyen
{
    class API
    {
        public static WebClient GetWebClient()
        {
            WebClient webClient = new WebClient();
            webClient.Headers["user-agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13";
            webClient.Headers["accept"] = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            return webClient;
        }
        public static void SetProgressIndicator(Grid grid, bool value, string text = "")
        {
            if (SystemTray.IsVisible)
            {
                if (SystemTray.ProgressIndicator == null)
                    SystemTray.ProgressIndicator = new ProgressIndicator();
                SystemTray.ProgressIndicator.Text = text;
                SystemTray.ProgressIndicator.IsIndeterminate = value;
                SystemTray.ProgressIndicator.IsVisible = value;
            }
            else
            {
                var spProgressIndicator = grid.FindName("spProgressIndicator") as StackPanel;
                if (spProgressIndicator == null)
                {
                    var progressBar = new ProgressBar { IsIndeterminate = true };
                    var textBlock = new TextBlock { Text = text, Name = "tbProgressIndicator" };
                    var stackpanel = new StackPanel { Margin = new Thickness(10, 0, 0, 0), Name = "spProgressIndicator", };
                    stackpanel.Children.Add(progressBar);
                    stackpanel.Children.Add(textBlock);
                    grid.Children.Add(stackpanel);
                    spProgressIndicator = stackpanel;
                }
                var tbProgressIndicator = grid.FindName("tbProgressIndicator") as TextBlock;
                tbProgressIndicator.Text = text;
                spProgressIndicator.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
            }
        }
        public static bool CheckWebClient(DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                //API.SetProgressIndicator(grid, false);
                if (!App.WorkOffline)
                {
                    App.WorkOffline = true;
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        if (e.Error.Message.Contains("NotFound"))
                            MessageBox.Show("Không thể kết nối đến server.");
                        else
                            MessageBox.Show(e.Error.Message);
                    });
                }
                return false;
            }
            App.WorkOffline = false;
            return true;
        }
        public static string GetVersion()
        {
            var nameHelper = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
            return nameHelper.Version.ToString();
        }
        public static void RateApp()
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
        }
        public static bool TrySaveFile(string fileName, string data)
        {
            try
            {
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (file.FileExists(fileName))
                    {
                        file.DeleteFile(fileName);
                    }
                    using (IsolatedStorageFileStream stream = file.OpenFile(fileName, FileMode.Create))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(data);
                            return true;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return false;
        }
        public static string TryReadFile(string fileName)
        {
            String sb = string.Empty;
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (myIsolatedStorage.FileExists(fileName))
                    {
                        StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));

                        sb = reader.ReadToEnd();

                        reader.Close();
                    }
                }
            }
            catch (Exception)
            {
            }
            return sb;
        }
        private static void SaveFileToIsolatedStorage(Uri fileUri, string _fileName)
        {

            var AppIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            var FileName = AppIsolatedStorage.CreateFile(_fileName);

            var FileData = Application.GetResourceStream(fileUri);

            byte[] bytes = new byte[4096];

            int Count;

            while ((Count = FileData.Stream.Read(bytes, 0, 4096)) > 0)
            {

                FileName.Write(bytes, 0, Count);

            }

            FileName.Close();

        }
        public static object GetPropValue(object src, string propName)
        {
            return src.GetType().GetProperty(propName).GetValue(src, null);
        }
        public static void PlayVideo(string videoUrl)
        {
            MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();

            mediaPlayerLauncher.Media = new Uri(videoUrl, UriKind.Absolute);
            mediaPlayerLauncher.Location = MediaLocationType.Data;
            mediaPlayerLauncher.Controls = MediaPlaybackControls.Pause | MediaPlaybackControls.FastForward | MediaPlaybackControls.Rewind;
            mediaPlayerLauncher.Orientation = MediaPlayerOrientation.Landscape;
            mediaPlayerLauncher.Show();
        }
        public static void SaveFavorites()
        {
            //var str = JsonConvert.SerializeObject(Home.ViewModel.favorites);
            //API.TrySaveFile("favorites", str);
        }
    }
}
